import axios from "axios"
import NProgress from "nprogress" // 进度条插件
import "nprogress/nprogress.css" 
import {Message} from "element-ui"

const req = axios.create({
  baseURL:"/api",
  timeout:10000,
})

// 请求拦截器
req.interceptors.request.use(
  config => {
    // 请求成功的拦截
    NProgress.start() // 进度条开始
    const token=localStorage.getItem("token")
    // console.log(token)
    if(token){
    config.headers.token=localStorage.getItem("token")
}
    return config
  },
  err => {
    // 请求失败的拦截
    console.log("请求失败",err)
    return Promise.reject(err)
  }
)
// 响应拦截器
req.interceptors.response.use(
  res => {
    // 响应成功的拦截
    NProgress.done() // 进度条结束
    if(res.data.code === 200){
      // console.log(res,'响应拦截')
      return Promise.resolve(res.data)
    }
    else{
      console.log("响应数据状态码非200",res)
      Message({
        message:"响应数据状态码非200 " + res.data.message,
        type:"error",
        duration: 2000
      })
      return Promise.reject(res.data.message || "未知错误，请联系网管")
    }
  },
  err => {
    // 响应失败的拦截,res.response.status !== 200时判断为响应失败
    console.log("响应失败",err.message,err.response)
    let message 
    if(err.response){
      message = err.response.status +" "+ err.response.statusText
    }
    else{
      message = "请求超时 " + err.message
    }
    NProgress.done() // 进度条结束
    Message({
      message,
      type:"error",
      duration: 2000
    })
    return Promise.reject(err.message)
  }
)

export default req 
